
# -*- coding:utf-8 -*-

import os
import fitz  # 导入PyMuPDF库，用于处理PDF文件
from PIL import Image  # 导入Pillow库的Image模块，用于图像处理

def convert_pdf_to_images(pdf_path, output_folder, resolution=2300, color_mode='rgb'):
    # 打开PDF文件
    pdf_document = fitz.open(pdf_path)
    new_single_folder = pdf_path.split('/')[-1].replace('.','')
    new_single_folder = os.path.join(output_folder,new_single_folder)
    if not os.path.exists(new_single_folder):
        os.makedirs(new_single_folder)
    # 遍历PDF中的每一页
    for page_number in range(len(pdf_document)):
        page = pdf_document[page_number]
        # 获取页面的原始大小（以点为单位）
        zoom_x = resolution / page.rect.width
        zoom_y = resolution / page.rect.height
        # 使用最小的缩放比例以确保整个页面都适应目标分辨率
        zoom = min(zoom_x, zoom_y)
        #zoom = min(1, 1)
        # 创建一个矩阵来应用缩放和抗锯齿
        mat = fitz.Matrix(zoom, zoom)
        # 将PDF页面转换为图片，指定分辨率、颜色模式和抗锯齿
        pix = page.get_pixmap(matrix=mat, alpha=False, colorspace=color_mode)
        # 定义输出图片的路径
        output_path = os.path.join(f'{new_single_folder}',f'page_{page_number + 1}.png')
        # 将像素图像转换为PIL的Image对象
        img = Image.frombytes("RGB", (pix.width, pix.height), pix.samples)
        # 保存图片
        img.save(output_path)

    # 关闭PDF文件
    pdf_document.close()

# 执行程序 
def process_files(in_folder_path,out_folder_path,resolution):
    if not os.path.exists(out_folder_path):
        os.mkdir(out_folder_path)
    # 遍历文件夹中的所有文件
    for root, dirs, files in os.walk(in_folder_path):
        for file in files:
            if file.endswith('.pdf'):
                convert_pdf_to_images(os.path.join(root,file),out_folder_path,resolution=resolution)

if __name__ == "__main__":
    # PDF文件夹路径
    pdf_path = "C:/E/temp/pic/"
    # 想要保存图片的文件夹路径
    output_folder = "C:/E/temp/pic/"
    # 设置分辨率
    resolution = 2300
    process_files(pdf_path, output_folder, resolution)
    

